<template>
  <el-dialog
    :title="!dataForm.brandId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="handleClose"

  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="140px"
    >
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo" prop="logo">
        <el-upload
          action=""
          :limit="1"
          :http-request="()=>{}"
          :on-change="changeLogo"
          :on-exceed="exceedLogo"
          :on-remove="removeLogo"
          :file-list="logoList"
          list-type="picture"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitLogo">上传到服务器
          </el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="介绍" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="介绍"></el-input>
      </el-form-item>
      <el-form-item label="显示状态" prop="showStatus">
        <el-switch
          v-model="dataForm.showStatus"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="检索首字母" prop="firstLetter">
        <el-input v-model="dataForm.firstLetter" placeholder="检索首字母"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <!-- 传入的必须是一个数字 -->
        <el-input v-model.number="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as qiniu from 'qiniu-js';
import {data} from "autoprefixer";

export default {
  components: {},
  data() {
    return {
      visible: false,
      logoList: [],
      dataForm: {
        brandId: 0,
        name: "",
        logo: "",
        logoFile: null,
        descript: "",
        showStatus: 1,
        firstLetter: "",
        sort: 0
      },
      dataRule: {
        name: [{required: true, message: "品牌名不能为空", trigger: "blur"}],
        logo: [
          {required: true, message: "品牌logo地址不能为空", trigger: "blur"}
        ],
        descript: [
          {required: true, message: "介绍不能为空", trigger: "blur"}
        ],
        showStatus: [
          {
            required: true,
            message: "显示状态[0-不显示；1-显示]不能为空",
            trigger: "blur"
          }
        ],
        firstLetter: [
          {
            validator: (rule, value, callback) => {
              if (value == "") {
                callback(new Error("首字母必须填写"));
              } else if (!/^[a-zA-Z]$/.test(value)) {
                callback(new Error("首字母必须a-z或者A-Z之间"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        sort: [
          {
            validator: (rule, value, callback) => {
              if (value == "" && value != 0) {
                callback(new Error("排序字段必须填写"));
              } else if (!Number.isInteger(value) || value < 0) {
                callback(new Error("排序必须是一个正整数"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    handleClose() {
      this.logoList = [];
      this.visible = false;
    },
    submitLogo() {
      if (this.dataForm.logoFile) {
        new Promise((resolve, reject) => {
            // 获取token
            this.$http({
              url: this.$http.adornUrl("/third/oss/policy"),
              method: "get"
            }).then(({data}) => {
              console.log(data);
              if (data && data.code === 0) {
                console.log("get token:" + data.token)
                resolve(data.token);
              } else {
                reject("获取token失败");
              }
            });
          }
        ).then(token => {
          return new Promise((resolve, reject) => {
            let date = this.$moment().format('YYYY-MM-DD')
            let fileName = date + "/" + this.dataForm.logoFile.uid + "_" + this.dataForm.logoFile.name;
            console.log(fileName);
            const observable = qiniu.upload(this.dataForm.logoFile.raw, fileName, token, {}, {})
            observable.subscribe({
              next: () => {
              },
              error: err => {
                reject(err);
              },
              complete: (res) => {
                console.log(res);
                this.dataForm.logo = res.key;
                resolve(res);
              }
            })
          })
        }).then(res => {
          this.$alert("上传成功");
        }).catch(err => {
          console.log(err);
        })
      } else {
        this.$alert("请选择图片后，再点击上传");
      }
    },
    removeLogo(file, fileList) {
      this.dataForm.logoFile = null;
      console.log(this.dataForm.logoFile)
    },
    exceedLogo(file, fileList) {
      this.$alert("只能上传一张图片，请先删除之前的logo");
    },
    changeLogo(file, fileList) {
      console.log(fileList)
      this.dataForm.logoFile = file;
      console.log(this.dataForm.logoFile)
      this.logoList[0] = {
        name: file.name,
        url: ""
      }
    },
    init(id) {
      this.dataForm.brandId = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.brandId) {
          this.$http({
            url: this.$http.adornUrl(
              `/product/brand/info/${this.dataForm.brandId}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.brand.name;
              this.dataForm.logo = data.brand.logo;
              this.dataForm.descript = data.brand.descript;
              this.dataForm.showStatus = data.brand.showStatus;
              this.dataForm.firstLetter = data.brand.firstLetter;
              this.dataForm.sort = data.brand.sort;

              //初始化图片
              this.logoList = [{
                name: data.brand.name,
                url: data.brand.logo
              }]
            }
          });
        } else {
          this.logoList = []
        }
        console.log(this.logoList)
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/product/brand/${!this.dataForm.brandId ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              brandId: this.dataForm.brandId || undefined,
              name: this.dataForm.name,
              logo: this.dataForm.logo,
              descript: this.dataForm.descript,
              showStatus: this.dataForm.showStatus,
              firstLetter: this.dataForm.firstLetter,
              sort: this.dataForm.sort
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
}
;
</script>
